<!-- 设备管理-设备列表页面 -->
<template>
  <div class="app-container" style="padding-bottom: 50px">
    <px-form v-show="showSearch" ref="queryRef" class="custom-form-ui" :model="queryParams" :inline="true" label-width="90px">
      <!-- <px-button style="margin-top: 0" type="primary">抄表任务</px-button> -->
      <px-button style="margin-top: 0" type="primary" plain @click="printFile()">打印</px-button>
      <!-- <px-button style="margin-top: 0" type="primary" plain @click="exportToExcel()">导出</px-button> -->
      <span style="float: right">
        <px-form-item label="日期">
          <px-date-picker v-model="queryParams.queryDate" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
        </px-form-item>
        <px-button style="margin-top: -17px" type="primary" icon="" @click="handleQuery('search')">查询</px-button>
      </span>
    </px-form>

    <px-table
      id="print-content"
      ref="tableElement"
      v-loading="loading"
      class="readingtable"
      :span-method="arraySpanMethod"
      :data="typeList"
      show-overflow-tooltip
      border
      :cell-style="cellStyle"
    >
      <!-- <px-table-column label="序号" align="center" prop="id" /> -->
      <px-table-column label="系统" prop="systemName">
        <template #default="scope">
          <span>{{ scope.row.systemName }}</span>
        </template>
      </px-table-column>

      <px-table-column label="名称" prop="name">
        <template #default="scope">
          <span style="color: #3b82f6; cursor: pointer" @click="spcshow(scope.row.spcJob)">{{ scope.row.name }}</span>
        </template>
      </px-table-column>

      <px-table-column label="抄表类型" width="160" prop="dataSource">
        <template #default="scope">
          <span>{{ scope.row.dataSource }}</span>
        </template>
      </px-table-column>

      <px-table-column label="自动计算值" prop="autoCalculateValue">
        <template #default="scope">
          <span>{{ scope.row.autoCalculateValue }}</span>
        </template>
      </px-table-column>
      <px-table-column label="修正值" prop="modifyValue">
        <template #default="scope">
          <px-input
            v-if="scope.row.edittable"
            v-model="scope.row.modifyValue"
            size="small"
            placeholder="请输入修正值"
            @blur="handelEdithiden(scope.$index, 'modifyValue')"
          />
          <span v-else class="modifyValue" @click="handelEdit(scope.$index, 'modifyValue')">
            <span v-if="scope.row.modifyValue > scope.row.autoCalculateValue" class="modifyValue" style="color: #ef4444; cursor: pointer">{{
              scope.row.modifyValue
            }}</span>
            <span v-if="scope.row.modifyValue < scope.row.autoCalculateValue" class="modifyValue" style="color: #10b981; cursor: pointer">{{
              scope.row.modifyValue
            }}</span>
            <span v-if="scope.row.modifyValue == scope.row.autoCalculateValue" class="modifyValue" style="cursor: pointer">{{
              scope.row.modifyValue
            }}</span>
          </span>
        </template>
      </px-table-column>
      <template #empty>
        <px-empty :image-size="150" />
      </template>
    </px-table>
    <img id="print-img" :src="imageUrl" />
    <px-table
      v-if="!addVisible && !detailVisible"
      v-loading="loading"
      class="readingtable"
      :span-method="arraySpanMethod"
      :data="typeList"
      show-overflow-tooltip
      border
      :cell-style="cellStyle"
    >
      <!-- <px-table-column label="序号" align="center" prop="id" /> -->
      <px-table-column label="系统" prop="systemName">
        <template #default="scope">
          <span>{{ scope.row.systemName }}</span>
        </template>
      </px-table-column>

      <px-table-column label="名称" prop="name">
        <template #default="scope">
          <span style="color: #3b82f6; cursor: pointer" @click="spcshow(scope.row.spcJob)">{{ scope.row.name }}</span>
        </template>
      </px-table-column>

      <px-table-column label="抄表类型" width="160" prop="dataSource">
        <template #default="scope">
          <span>{{ scope.row.dataSource }}</span>
        </template>
      </px-table-column>

      <px-table-column label="自动计算值" prop="autoCalculateValue">
        <template #default="scope">
          <span>{{ scope.row.autoCalculateValue }}</span>
        </template>
      </px-table-column>
      <px-table-column label="修正值" prop="modifyValue">
        <template #default="scope">
          <px-input
            v-if="scope.row.edittable"
            v-model="scope.row.modifyValue"
            size="small"
            placeholder="请输入修正值"
            @blur="handelEdithiden(scope.$index, 'modifyValue')"
          />
          <span v-else class="modifyValue" @click="handelEdit(scope.$index, 'modifyValue')">
            <span v-if="scope.row.modifyValue > scope.row.autoCalculateValue" class="modifyValue" style="color: #ef4444; cursor: pointer">{{
              scope.row.modifyValue
            }}</span>
            <span v-if="scope.row.modifyValue < scope.row.autoCalculateValue" class="modifyValue" style="color: #10b981; cursor: pointer">{{
              scope.row.modifyValue
            }}</span>
            <span v-if="scope.row.modifyValue == scope.row.autoCalculateValue" class="modifyValue" style="cursor: pointer">{{
              scope.row.modifyValue
            }}</span>
          </span>
        </template>
      </px-table-column>
      <px-table-column fixed="right" label="操作" align="center" width="140">
        <template #default="scope">
          <!-- <px-button v-has="'ACCOUNTINGLIST_DETAIL'" link type="primary" @click="handleDetail(scope.row.id)">
            <px-tooltip class="box-item" content="详情" placement="top">
              <px-icon><Tickets /></px-icon> </px-tooltip
          ></px-button> -->
          <px-button
            v-if="scope.row.status != 'INVALID'"
            v-has="'ACCOUNTINGLIST_EDITOR'"
            link
            type="primary"
            @click="handelEdit(scope.$index, 'modifyValue')"
          >
            <px-tooltip class="box-item" content="编辑" placement="top">
              <px-icon><EditPen /></px-icon> </px-tooltip
          ></px-button>
          <px-button v-has="'ACCOUNTINGLIST_DETAIL'" link type="primary" @click="handleDetail(scope.row.pointNumber)">
            <px-tooltip class="box-item" content="历史记录" placement="top">
              <px-icon><Time /></px-icon> </px-tooltip
          ></px-button>
          <!-- <px-button v-if="scope.row.status != 'INVALID'" v-has="'ACCOUNTINGLIST_DELETE'" link type="danger" @click="handleDelete(scope.row)"
            ><px-tooltip class="box-item" content="删除" placement="top">
              <px-icon><Delete /></px-icon> </px-tooltip
          ></px-button> -->
        </template>
      </px-table-column>
      <template #empty>
        <px-empty :image-size="150" />
      </template>
    </px-table>

    <!-- spc窗口 -->
    <px-dialog v-model="innerVisible" draggable clickHideContent width="1372" title="SPC指标" append-to-body align-center>
      <px-form style="position: relative" class="custom-form-ui" :model="queryParams" :inline="true" label-width="90px">
        <px-radio-group v-model="timePeriod" style="position: absolute; top: 0; margin-left: 24px" @change="setTimePeriod()">
          <px-radio-button label="minutes">分钟</px-radio-button>
          <px-radio-button label="hour">小时</px-radio-button>
          <px-radio-button label="day">天</px-radio-button>
          <px-radio-button label="week">周</px-radio-button>
          <px-radio-button label="months">月</px-radio-button>
        </px-radio-group>
        <px-form-item label="时间日期" style="margin-left: 302px">
          <px-date-picker
            v-model="dateSpc"
            type="datetimerange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            :shortcuts="shortcuts"
            :default-time="defaultTime"
          />
        </px-form-item>
        <px-button style="margin-top: -17px" type="primary" icon="" @click="handleSpcAnalysis(detailjobId)">搜索</px-button>
        <px-button style="margin-top: -17px" icon="" @click="resetQuery2">重置</px-button>
      </px-form>
      <div class="spcchart">
        <chartsSearch
          :name="equipdata.indicatorName"
          :startValue="equipdata.startValue"
          :step="equipdata.step"
          :usl="equipdata.uslValue"
          :ucl="equipdata.uclValue"
          :uwl="equipdata.uwlValue"
          :target="equipdata.targetValue"
          :lwl="equipdata.lwlValue"
          :lcl="equipdata.lclValue"
          :lsl="equipdata.lslValue"
          :SpcAnalysis="SpcAnalysis"
          :pointUnit="pointUnit"
          :width="'1293px'"
          :height="'270px'"
        />
      </div>
      <div class="detailmain2">
        <px-tabs v-model="activeName" class="equipment-tabs">
          <px-tab-pane name="all">
            <template #label>
              <p class="pane-bottom">ALARM({{ totalCount }})</p>
              <p class="pane-line" />
            </template>
          </px-tab-pane>

          <px-tab-pane name="ooc">
            <template #label>
              <p class="pane-bottom">OOC({{ totalOocCount }})</p>
              <p class="pane-line" />
            </template>
          </px-tab-pane>
          <px-tab-pane name="oow">
            <template #label>
              <p class="pane-bottom">OOW({{ totalOowCount }})</p>
              <p class="pane-line" />
            </template>
          </px-tab-pane>
          <px-tab-pane name="oos">
            <template #label>
              <p class="pane-bottom">OOS({{ totalOosCount }})</p>
              <p class="pane-line" />
            </template>
          </px-tab-pane>
        </px-tabs>
      </div>
      <div style="padding: 20px 24px; background: white">
        <Alarm :activeName="activeName" :jobIdList="[detailjobId]" :dateSpc="dateSpc" />
      </div>
    </px-dialog>
    <px-dialog v-model="historyVisible" draggable clickHideContent width="1372" title="抄表修正历史记录" append-to-body align-center>
      <px-table
        v-loading="loading"
        :cell-style="cellStyle2"
        :data="ModifyHistoryList"
        height="calc(100vh - 339px)"
        show-overflow-tooltip
        highlight-current-row
        border
      >
        <px-table-column label="系统" prop="systemName">
          <template #default="scope">
            <span>{{ scope.row.systemName }}</span>
          </template>
        </px-table-column>
        <px-table-column label="名称" prop="gasType">
          <template #default="scope">
            <span>{{ scope.row.name }}</span>
          </template>
        </px-table-column>
        <px-table-column label="抄表类型" prop="dataSource">
          <template #default="scope">
            <span>{{ scope.row.dataSource }}</span>
          </template>
        </px-table-column>
        <px-table-column label="自动计算值" prop="autoCalculateValue">
          <template #default="scope">
            <span>{{ scope.row.autoCalculateValue }}</span>
          </template>
        </px-table-column>
        <px-table-column label="修正值" prop="modifyValue">
          <template #default="scope">
            <!-- <span :style="{ color: scope.row.modifyValue > scope.row.autoCalculateValue ? '#EF4444' : '#10B981' }">{{ scope.row.modifyValue }}</span> -->
            <span v-if="scope.row.modifyValue > scope.row.autoCalculateValue" class="modifyValue" style="color: #ef4444; cursor: pointer">{{
              scope.row.modifyValue
            }}</span>
            <span v-if="scope.row.modifyValue < scope.row.autoCalculateValue" class="modifyValue" style="color: #10b981; cursor: pointer">{{
              scope.row.modifyValue
            }}</span>
            <span v-if="scope.row.modifyValue == scope.row.autoCalculateValue" class="modifyValue" v style="cursor: pointer">{{
              scope.row.modifyValue
            }}</span>
          </template>
        </px-table-column>
        <px-table-column label="修正时间" prop="updateTime">
          <template #default="scope">
            <span>{{ scope.row.updateTime }}</span>
          </template>
        </px-table-column>
        <px-table-column label="修正人" prop="updater">
          <template #default="scope">
            <span>{{ scope.row.updater }}</span>
          </template>
        </px-table-column>
        <template #empty>
          <px-empty :image-size="150" />
        </template>
      </px-table>

      <pagination
        v-show="total2 > 0"
        v-model:page="queryParams2.pageNum"
        v-model:limit="queryParams2.pageSize"
        style="margin-bottom: -10px"
        :total="total2"
        @pagination="getRukuList"
      />
    </px-dialog>
    <div class="px-dialog-footer">
      <px-button type="primary" plain @click="tableReading()">抄表修正</px-button>
      <px-button type="primary" @click="equipopenDetailsubmitForm()">提交</px-button>
    </div>
  </div>
</template>

<script setup name="Dict" lang="ts">
defineOptions({
  name: "SystemDataDict"
});
// import { router } from "@/router";
import { ArrowLeft } from "@px-ui/icons-vue";
import { useRoute } from "vue-router";
import { PxMessage, PxMessageBox } from "px-ui";
import { getCurrentInstance, ref, toRefs, reactive, onMounted } from "vue";
import { getToken } from "@/utils/auth";
import { queryChildByTypeCodeAndItemValue } from "@/api/waterClass";

import {
  balancequeryStatisticsList,
  balanceupdateStatistics,
  balanceaddSubmitHistory,
  balancequeryStatisticsModifyHistory
} from "@/api/waterBalance";
import printJS from "print-js";
import * as XLSX from "xlsx/xlsx.mjs";
import chartsSearch from "../components/chartsSearch.vue";
import Alarm from "../components/alarm.vue";
import { spcIndicatorquerySpcAnalysisResultList, spcquerySpcAnalysis } from "@/api/spc";
import html2canvas from "html2canvas";
const totalCount = ref("");
const totalOocCount = ref("");
const totalOosCount = ref("");
const totalOowCount = ref("");
const timePeriod = ref("minutes");
const tableElement = ref(null);
const imageUrl = ref(null);
const printFile = () => {
  console.log(tableElement.value);
  if (tableElement.value) {
    const content = document.getElementById("print-content");
    let rect = content.getBoundingClientRect();
    html2canvas(content)
      .then(canvas => {
        console.log(rect);
        imageUrl.value = canvas.toDataURL("image/png");
        setTimeout(() => {
          printJS({
            printable: "print-img",
            type: "html",
            style: `
         @media print{
          body,html{
            margin:0;
            padding:0;
            width:100%;
            height:${rect.height * (1110 / rect.width)}px;
          }
          #print-img {
            width:1110px;
            transform-origin:top left;
          }
          img.print-full-page{
            position:absolute;
            top:0;
            left:0;
            width:100%;
            height:100%;
            object-fit:cover;
            page-break-before:always;
            page-break-after:always;
          }
         @page {margin: 1cm;}
          }
          `, // 去掉页眉页脚
            scanStyles: false,
            // targetStyles: ['*'],
            header: null,
            documentTitle: "水课抄表"
          });
        }, 100);
      })
      .catch(error => {
        console.log("Error", error);
      });
  }
};
const exportToExcel = () => {
  // 创建一个工作簿
  const wb = XLSX.utils.book_new();

  // 转换json到工作表
  let wsData = [
    ["系统", "名称", "抄表类型", "自动计算值", "修正值"],
    ...typeList.value.map(item => [item.systemName, item.name, item.dataSource, item.autoCalculateValue, item.modifyValue])
  ];
  const ws = XLSX.utils.json_to_sheet(wsData);

  // 添加工作表到工作簿
  XLSX.utils.book_append_sheet(wb, ws, "Sheet1");

  // 生成excel文件的blob对象
  const wbout = XLSX.write(wb, { bookType: "xlsx", type: "binary" });

  // 创建一个临时的a标签用于下载
  const blob = new Blob([s2ab(wbout)], { type: "application/octet-stream" });

  // 创建一个指向文件的URL
  const url = window.URL.createObjectURL(blob);

  // 创建一个a标签并模拟点击进行下载
  const link = document.createElement("a");
  link.href = url;
  link.setAttribute("download", "水课抄表.xlsx");
  document.body.appendChild(link);
  link.click();

  // 清理工作
  window.URL.revokeObjectURL(url);
  document.body.removeChild(link);

  // 字符串转ArrayBuffer
  function s2ab(s) {
    const buf = new ArrayBuffer(s.length);
    const view = new Uint8Array(buf);
    for (let i = 0; i < s.length; i++) {
      view[i] = s.charCodeAt(i) & 0xff;
    }
    return buf;
  }
};

const defaultTime: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 1), new Date(2000, 1, 1, 23, 59, 59)];
const shortcuts = [
  {
    text: "本日",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setHours(0, 0, 0, 0);
      start.setTime(start.getTime());
      return [start, end];
    }
  },
  {
    text: "近7天",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    }
  },
  {
    text: "近30天",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    }
  },
  {
    text: "本月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setDate(1);
      start.setHours(0, 0, 0, 0);
      start.setTime(start.getTime());
      return [start, end];
    }
  },
  {
    text: "本季度",
    value: () => {
      const end = new Date();
      const start = new Date();
      let currenMonth = start.getMonth();
      let quarter = Math.floor((currenMonth + 3) / 3) - 1;
      start.setMonth(quarter * 3, 1);
      start.setDate(1);
      start.setHours(0, 0, 0, 0);
      start.setTime(start.getTime());
      return [start, end];
    }
  }
];
onMounted(() => {
  if (localStorage.getItem("chukuList")) {
  }
});

const tableReading = () => {
  console.log(oldList.value[0]);
  console.log(typeList.value[0]);
  let celllist = typeList.value.filter(item2 => {
    let found = oldList.value.find(item1 => item1.id === item2.id);
    return !found || found.modifyValue !== item2.modifyValue;
  });

  let historyList = celllist.map(item => {
    return {
      id: item.id,
      modifyValue: item.modifyValue
    };
  });
  console.log(historyList);
  balanceupdateStatistics({ updateList: historyList }).then((response: any) => {
    PxMessage({
      message: "抄表修正成功",
      type: "success"
    });

    getList();
  });
};
const { proxy }: any = getCurrentInstance();
const dateSpc = ref([]);
const typeList = ref([]);
const progressVisible = ref(false);
const equipopenDetail = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const addVisible = ref(false);
const detailVisible = ref(false);
const innerVisible = ref(false);
const historyVisible = ref(false);
const total = ref(0);
const total2 = ref(0);
const dateRange = ref([]);
const activeName = ref("all");
const detailjobId = ref("");
// 图片是否上传完，是否可以保存
const buttonTitle = ref("");
const data = reactive({
  liquidList: [],
  rukuList: [],
  transportCompanyList: [],
  receiveCompanyList: [],
  typeIdList: [],
  categoryList: [],
  equipmentTypeList: [],
  positionList: [],
  selectRukuList: {},
  okselectRukuList: [],
  equipmentDeptList: [],
  modelIdList: [],
  form: {},
  wasteUnitoptions: [
    {
      value: "克",
      label: "克"
    },
    {
      value: "千克",
      label: "千克"
    },
    {
      value: "吨",
      label: "吨"
    }
  ],
  photoStatusFlag: false,
  fileStatusFlag: false,
  SpcAnalysis: [],
  equipdata: {
    id: "",
    jobId: "",
    indicatorName: "",
    classCode: "",
    systemCode: "",
    indicatorLevel: "",
    point: "",
    pointUnit: "",
    step: 0,
    startValue: 0,
    targetValue: 0,
    uclValue: 0,
    lclValue: 0,
    uwlValue: 0,
    lwlValue: 0,
    uslValue: 0,
    lslValue: 0,
    u3lValue: 0,
    l3lValue: 0
  },
  queryParams: {
    queryDate: new Date().toISOString().split("T")[0]
  },
  queryParams2: {
    orderByColumn: "",
    isAsc: "",
    emissionFactorName: "",
    factorSource: "",
    releaseYear: "",
    orderBy: "",
    pageNum: 1,
    pageSize: 20
  },
  rules: {
    name: [{ required: true, message: "不能为空", trigger: "blur" }],
    serialNumber: [{ required: true, message: "不能为空", trigger: "blur" }],
    category: [{ required: true, message: "不能为空", trigger: "change" }],
    activityLevelUnit: [{ required: true, message: "不能为空", trigger: "change" }],
    emissionFactorName: [{ required: true, message: "不能为空", trigger: "blur" }],
    value: [{ required: true, message: "不能为空", trigger: "blur" }],
    factorSource: [{ required: true, message: "不能为空", trigger: "blur" }],
    releaseYear: [{ required: true, message: "不能为空", trigger: "blur" }],
    unit: [{ required: true, message: "不能为空", trigger: "blur" }],
    unitConversionRatio: [{ required: true, message: "不能为空", trigger: "blur" }],
    emissionCategory: [{ required: true, message: "不能为空", trigger: "change" }]
  },
  headers: {
    Authorization: "Bearer " + getToken().accessToken || ""
  },
  moduleName: "",
  dialogImageUrl: "",
  imageVisible: false,
  levelUnitList: [],
  energyList: [],
  categoryTypeList: [],
  SourceList: [],
  selectrow: null,
  nameSpanMap: {},
  oldList: [],
  ModifyHistoryList: []
});
const selectyinzi = () => {
  getRukuList();
  innerVisible.value = true;
};
const cellStyle = ({ row, column, rowIndex, columnIndex }) => {
  if (columnIndex === 4) {
    if (row.modifyValue !== null) {
      if (row.modifyValue > row.autoCalculateValue) {
        return { background: "#FFDADA !important" };
      }
      if (row.modifyValue < row.autoCalculateValue) {
        return { background: "#DFFFEA !important" };
      }
    }
  } else {
    return {};
  }
  // return { background: "#FFDADA" };
};
const cellStyle2 = ({ row, column, rowIndex, columnIndex }) => {
  if (columnIndex === 4) {
    if (row.modifyValue !== null) {
      if (row.modifyValue > row.autoCalculateValue) {
        return { background: "#FFDADA !important" };
      }
      if (row.modifyValue < row.autoCalculateValue) {
        return { background: "#DFFFEA !important" };
      }
    }
  } else {
    return {};
  }
  // return { background: "#FFDADA" };
};
const { selectRukuList, queryParams, queryParams2, form, equipdata, rukuList, selectrow, nameSpanMap, oldList, ModifyHistoryList, SpcAnalysis } =
  toRefs(data);
const pointUnit = ref("空");
const arraySpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  if (columnIndex === 0) {
    if (nameSpanMap.value[row.systemName] && rowIndex === nameSpanMap.value[row.systemName].rowIndex) {
      return {
        rowspan: nameSpanMap.value[row.systemName].rowspan,
        colspan: 1
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0
      };
    }
  }
};
const getqueryCategoryList = () => {
  // queryChildByTypeCodeAndItemValue({
  //   value: "EMISSION_FACTOR_SOURCE",
  //   typeCode: "BICARBON"
  // }).then((response: any) => {
  //   SourceList.value = response;
  // });
};

const setTimePeriod = () => {
  handleSpcAnalysis(detailjobId.value);
};
const spcshow = async val => {
  innerVisible.value = true;
  //console.log(equipdata);
  detailjobId.value = val;
  const end = new Date();
  const start = new Date();
  start.setHours(0, 0, 0, 0);
  start.setTime(start.getTime());
  dateSpc.value = [formatDate(start), formatDate(end)];
  console.log(dateSpc.value);
  handleSpcAnalysis(val);
};
const handleSpcAnalysis = spcjob => {
  spcquerySpcAnalysis({
    jobIdList: [spcjob],
    // jobIdList: ["WATER_BAL_R_UPW0010_1"],
    timePeriod: timePeriod.value,
    startTime: dateSpc.value[0],
    endTime: dateSpc.value[1]
  }).then((response: any) => {
    SpcAnalysis.value = response;
  });
  spcIndicatorquerySpcAnalysisResultList({
    pageNum: queryParams2.value.pageNum,
    pageSize: queryParams2.value.pageSize,
    jobIdList: [detailjobId.value],
    alarmType: "",
    startTime: dateSpc.value[0],
    endTime: dateSpc.value[1]
  }).then(res => {
    if (res != null) {
      totalCount.value = res.totalCount;
      totalOocCount.value = res.totalOocCount;
      totalOosCount.value = res.totalOosCount;
      totalOowCount.value = res.totalOowCount;
    } else {
      totalCount.value = 0;
      totalOocCount.value = 0;
      totalOosCount.value = 0;
      totalOowCount.value = 0;
    }
  });
};

function formatDate(date) {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  const h = date.getHours().toString().padStart(2, "0");
  const m = date.getMinutes().toString().padStart(2, "0");
  const s = date.getSeconds().toString().padStart(2, "0");
  return `${year}-${month}-${day} ${h}:${m}:${s}`;
}
const addsave = () => {};
getqueryCategoryList();
function getRukuList() {
  loading.value = true;

  emissionFactorquery(queryParams2.value).then((response: any) => {
    rukuList.value = response.data;
    total2.value = response.total;
    loading.value = false;
  });
}

const handelEdit = (index, propName) => {
  typeList.value[index].edittable = true;
};
const handelEdithiden = (index, propName) => {
  typeList.value.forEach(item => {
    item.edittable = false;
  });
};
function getList() {
  loading.value = true;
  balancequeryStatisticsList(queryParams.value).then((response: any) => {
    nameSpanMap.value = {};
    let currentSpan = 0;
    if (response.length > 0) {
      response.forEach((row, index) => {
        if (index === 0 || response[index - 1].systemName !== row.systemName) {
          currentSpan = 1;
          nameSpanMap.value[row.systemName] = {
            rowIndex: index,
            rowspan: 1
          };
        } else {
          currentSpan++;
          nameSpanMap.value[row.systemName].rowspan = currentSpan;
        }
      });
    }
    oldList.value = JSON.parse(JSON.stringify(response));
    typeList.value = response;
    oldList.value.map(item => (item.edittable = false));
    typeList.value.map(item => (item.edittable = false));
    loading.value = false;
  });
}
const removechukuList = () => {
  localStorage.removeItem("chukuList");
};
/** 取消按钮 */

/** 表单重置 */
function reset() {
  form.value = {
    id: undefined,
    dictionaryName: undefined,
    dictionaryType: undefined,
    status: "VALID",
    remarks: undefined
  };
  proxy.resetForm("dictRef");
}
/** 搜索按钮操作 */
function handleQuery(type) {
  getList();
}
function handleQuery2(type) {
  if (type == "search") {
    queryParams2.value.pageNum = 1;
  }
  getRukuList();
}
/** 重置按钮操作 */
function resetQuery() {
  queryParams.value = {
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize,
    orderByColumn: "",
    isAsc: "",
    dictWasteCode: "",
    startTime: "",
    endTime: "",
    status: "",
    orderBy: ""
  };
  dateRange.value = [];
  handleQuery("reset");
}

function resetQuery2() {
  queryParams2.value = {
    pageNum: queryParams2.value.pageNum,
    pageSize: queryParams2.value.pageSize,
    orderByColumn: "",
    isAsc: "",
    emissionFactorName: "",
    factorSource: "",
    releaseYear: "",
    orderBy: ""
  };
  dateRange.value = [];
  handleQuery2("reset");
}

/** 新增按钮操作 */
function handleAdd() {
  buttonTitle.value = "新增";
  addVisible.value = true;
  equipdata.value = {
    name: "",
    serialNumber: "",
    category: "",
    relatedEnergy: "",
    emissionFactorId: "",
    emissionFactorName: "",
    unit: "",
    factorSource: "",
    activityLevelUnit: "",
    unitConversionRatio: null,
    emissionCategory: "",
    standardValueList: [],
    createByName: "",
    updateByName: ""
  };
}
const handleDetail = async val => {
  historyVisible.value = true;
  const data = await balancequeryStatisticsModifyHistory({ pointNumber: val, readingDate: queryParams.value.queryDate });

  ModifyHistoryList.value = data.historyDTO;
  // equipdata.value = data;
  console.log(ModifyHistoryList.value);
};

/** 多选框选中数据 */
function handleSelectionChange2(selection) {
  console.log(selection);
  selectRukuList.value = selection;
}

// const addRukudetails = () => {
//   equipdata.value.details = [...equipdata.value.details, ...selectRukuList.value];
//   let seenIds = new Set();
//   let uniqueArr = [];
//   equipdata.value.details.forEach(obj => {
//     if (!seenIds.has(obj.inboundNumber)) {
//       uniqueArr.push(obj);
//       seenIds.add(obj.inboundNumber);
//     }
//   });
//   equipdata.value.details = [];
//   if (setChukuList(uniqueArr) == true) {
//     progressVisible.value = false;
//     equipdata.value.details = uniqueArr;
//   }
// };

let setChukuList = uniqueArr => {
  if (uniqueArr.length === 0) {
    PxMessage({
      message: "请选择要出库的数据",
      type: "error"
    });
    return false;
  }
  const firstname = uniqueArr[0].wasteName;
  for (let i = 1; i < uniqueArr.length; i++) {
    if (uniqueArr[i].wasteName != firstname) {
      PxMessage({
        message: "请选择相同的废弃物",
        type: "error"
      });
      return false;
    }
  }
  return true;
};

const handleDeleteRuku = row => {
  // console.log(row);
  equipdata.value.details = equipdata.value.details.filter(item => item != row);
};
const saveYinziku = () => {
  equipdata.value.emissionFactorId = selectrow.value.id;
  equipdata.value.emissionFactorName = selectrow.value.name;
  equipdata.value.value = selectrow.value.value;
  equipdata.value.unit = selectrow.value.unit;
  equipdata.value.factorSource = selectrow.value.factorSource;
  equipdata.value.releaseYear = selectrow.value.releaseYear;
  innerVisible.value = false;
  //selectrow
};
/** 提交按钮 */

const equipopenDetailsubmitForm = () => {
  balanceaddSubmitHistory({
    reportName: "水量统计",
    reportDate: queryParams.value.queryDate
  }).then(res => {
    PxMessage({
      message: "提交成功",
      type: "success"
    });
  });
};
/** 删除按钮操作 */
function handleDelete(row) {
  PxMessageBox.confirm('是否确认删除"' + row.name + '"？', "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    confirmButtonClass: "px-button--danger",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      const data = await facilitydelete({ id: row.id });
      PxMessage({
        message: "删除成功",
        type: "success"
      });
      getList();
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  const dictIds = [];
  dictIds.push(...ids.value);
  const params = { ids: dictIds };
  proxy.download("post", "/operation/api/v1/water/hazardWasteOut/export", params, "危险废弃物出库.xlsx");
}
getList();
</script>
<style scoped lang="scss">
.addEquip {
  position: absolute;
  top: 0;
  top: 5px;
  left: 0;
  width: calc(100% - 48px);
  height: calc(100% - 40px);
  margin: 24px;
  background: white;
}

.editorEquip {
  position: absolute;
  top: 0;
  top: 5px;
  left: 0;
  width: calc(100% - 48px);
  height: calc(100% - 40px);
  margin: 24px;
  background: white;
}

.px-dialog-footer {
  position: absolute;
  bottom: 0;
  left: 0;
  z-index: 2002;
  width: 100%;
  height: 50px;
  padding-top: 10px;
  padding-right: 34px;
  text-align: right;
  background: white;
  box-shadow: 0 0 10px 0 rgb(0 0 0 / 16%);
}

.card-header {
  min-height: 40px;
  padding: 14px 15px 7px !important;
  cursor: pointer;
  user-select: none;
  background: #e7eefb;
}

.card-title {
  float: left;
  line-height: 14px;
}

.card-main {
  float: left;
  margin: -3px 8px 0 5px;
  cursor: pointer;
}

.box-card1 {
  width: calc(100% - 48px);
  margin: 24px;
  overflow: hidden;
  border: 1px solid #dfdfdf;
  border-radius: 4px;
}

.box-card2 {
  width: calc(100% - 48px);
  margin: 24px;
  overflow: hidden;
  border: 1px solid #dfdfdf;
  border-radius: 4px;
}

.box-card3 {
  width: calc(100% - 48px);
  margin: 24px;
  overflow: hidden;
  border: 1px solid #dfdfdf;
  border-radius: 4px;
}

.box-card4 {
  width: calc(100% - 48px);
  height: 261px;
  margin: 24px;
  overflow: hidden;
  border: 1px solid #dfdfdf;
  border-radius: 4px;
}

.demo-form-inline {
  .px-input {
    --px-input-width: calc(100% - 70px);
  }

  .px-form-item {
    width: 100%;
  }

  .px-textarea__inner {
    width: calc(100% - 100px) !important;
  }

  .px-form-item__label {
    font-weight: 400 !important;
  }
}

.form-div {
  padding: 24px;

  .px-row {
    margin-bottom: 16px;
  }
}

.px-icon {
  font-size: 16px !important;
}

:deep(.px-tabs--top .px-tabs__item.is-top.is-active) {
  border: none;

  .pane-bottom {
    line-height: 30px;
    border-bottom: 2px solid #3b82f6;
  }
}

:deep(.px-tabs .px-tabs__item) {
  .pane-bottom {
    line-height: 30px;
  }
}

.pane-line {
  position: absolute;
  top: 12px;
  right: 0;
  height: 15px;
  color: #dcdcdc;
  border-left: 1px solid #dcdcdc;
}

:deep(.custom-form-ui .px-form-item) {
  width: 250px !important;
}

.filename {
  position: absolute;
  bottom: -30px;
  width: 96px;
  overflow: hidden;
  color: rgb(166 167 172);
  text-overflow: ellipsis;
  white-space: nowrap;
}

:deep(.px-descriptions__label.px-descriptions__cell.is-bordered-label) {
  width: 166px;
  background: #e7eefb;
  border: 1px solid #dfdfdf;
}

:deep(.px-descriptions__body .px-descriptions__table.is-bordered .px-descriptions__cell) {
  border: 1px solid #dfdfdf;
}

.cell-item {
  text-align: right;
}

:deep(.px-table__header) {
  thead {
    tr {
      background-color: #e7eefb !important;

      th {
        font-size: 14px;
        font-weight: bold;
        color: #000;
        background-color: #e7eefb !important;
      }
    }
  }
}

:deep(.px-table--isfixedHeader .px-table__header-wrapper .px-table-fixed-column--right) {
  background-color: #e7eefb !important;
}

.modifyValue {
  display: inline-block;
  width: 100%;
}

#print-content {
  position: absolute;
  left: -20000px;
}

#print-img {
  position: absolute;
  left: -20000px;
  width: 800px;
}

:deep(.px-table .cell) {
  line-height: 30px;
  vertical-align: middle;
}
</style>
